const fs = require('fs');
const path = require('path');
const multer = require('multer');
const jsonFilePath = path.join(__dirname, '../book.json');

// 读取 JSON 文件中的数据
const readJsonData = () => {
    const data = fs.readFileSync(jsonFilePath, 'utf8');
    return JSON.parse(data);
};

// 写入数据到 JSON 文件
const writeJsonData = (data) => {
    fs.writeFileSync(jsonFilePath, JSON.stringify(data, null, 2), 'utf8');
};

// 查询书籍信息
exports.getBooks = (req, res) => {
    const { title, author, page = 1, pageSize = 10 } = req.query;
    let books = readJsonData();

    if (title) {
        books = books.filter(book => book.title.toLowerCase().includes(title.toLowerCase()));
    }

    if (author) {
        books = books.filter(book => book.author.toLowerCase().includes(author.toLowerCase()));
    }

    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + parseInt(pageSize);
    const paginatedBooks = books.slice(startIndex, endIndex);

    res.json({
        code: 0,
        message: '成功',
        count: books.length,
        content: paginatedBooks
    });
};

// 添加书籍
exports.addBook = (req, res) => {
    const { title, author, detail, cover } = req.body;

    if (!title || !author || !detail) {
        return res.status(400).json({ error: '缺少必要的书籍信息' });
    }

    let books = readJsonData();
    const newBook = {
        id: books.length ? books[books.length - 1].id + 1 : 1,
        title,
        author,
        detail,
        cover: cover || ''
    };

    books.push(newBook);
    writeJsonData(books);

    res.json({ code: 0, message: '书籍添加成功', book: newBook });
};

// 上传封面
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'uploads/');
    },
    filename: (req, file, cb) => {
        const ext = path.extname(file.originalname);
        cb(null, Date.now() + ext);
    }
});

const upload = multer({ storage: storage });

// 处理图片上传
exports.uploadCover = upload.single('file');

// 编辑书籍
exports.editBook = (req, res) => {
    const { id, title, author, detail, cover } = req.body;

    if (!id || !title || !author || !detail) {
        return res.status(400).json({ error: '缺少必要的书籍信息' });
    }

    let books = readJsonData();
    const bookIndex = books.findIndex(book => book.id === parseInt(id));

    if (bookIndex === -1) {
        return res.status(404).json({ error: '书籍未找到' });
    }

    books[bookIndex] = {
        ...books[bookIndex],
        title,
        author,
        detail,
        cover: cover || books[bookIndex].cover
    };

    writeJsonData(books);

    res.json({ code: 0, message: '书籍编辑成功', book: books[bookIndex] });
};

// 删除书籍
exports.deleteBook = (req, res) => {
    const { id } = req.body;
    const bookId = parseInt(id);

    let books = readJsonData();
    const bookIndex = books.findIndex(book => book.id === bookId);

    if (bookIndex === -1) {
        return res.status(404).json({ code: 1, message: '书籍不存在' });
    }

    books.splice(bookIndex, 1);
    writeJsonData(books);

    res.json({ code: 0, message: '书籍删除成功' });
};
